<template>
  <div class="history-page">
    <!-- 筛选栏 -->
    <div class="filter-bar">
      <van-tabs v-model:active="activeStatus" @click-tab="onStatusChange">
        <van-tab name="" title="全部"></van-tab>
        <van-tab name="completed" title="已完成"></van-tab>
        <van-tab name="processing" title="生成中"></van-tab>
        <van-tab name="failed" title="失败"></van-tab>
      </van-tabs>
    </div>
    
    <!-- 历史记录列表 -->
    <div class="history-list">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div 
            v-for="task in historyList" 
            :key="task.id"
            class="history-item"
            @click="viewTask(task)"
          >
            <div class="task-images">
              <!-- 原图 -->
              <div class="image-container">
                <img :src="task.original_image_url" alt="原图" />
                <div class="image-label">原图</div>
              </div>
              
              <!-- 箭头 -->
              <div class="arrow">
                <van-icon name="arrow" />
              </div>
              
              <!-- 生成图 -->
              <div class="image-container">
                <img 
                  v-if="task.generated_image_url" 
                  :src="task.generated_image_url" 
                  alt="生成图" 
                />
                <div v-else class="image-placeholder">
                  <van-loading v-if="task.status === 'processing'" size="20px" />
                  <van-icon v-else-if="task.status === 'failed'" name="close" />
                  <van-icon v-else name="photo" />
                </div>
                <div class="image-label">生成图</div>
              </div>
            </div>
            
            <div class="task-info">
              <div class="task-header">
                <h3 class="task-title">{{ task.style_template?.name || '未知风格' }}</h3>
                <span class="task-status" :class="task.status">
                  {{ getStatusText(task.status) }}
                </span>
              </div>
              
              <div class="task-details">
                <div class="detail-item">
                  <van-icon name="clock-o" />
                  <span>{{ formatTime(task.created_at) }}</span>
                </div>
                
                <div class="detail-item" v-if="task.completed_at">
                  <van-icon name="checked" />
                  <span>{{ formatTime(task.completed_at) }}</span>
                </div>
                
                <div class="detail-item">
                  <van-icon name="photo" />
                  <span>{{ task.width }}×{{ task.height }}</span>
                </div>
              </div>
              
              <!-- 自定义提示词 -->
              <p v-if="task.custom_prompt" class="custom-prompt">
                <van-icon name="edit" />
                {{ task.custom_prompt }}
              </p>
              
              <!-- 错误信息 -->
              <p v-if="task.status === 'failed' && task.error_message" class="error-message">
                <van-icon name="warning" />
                {{ task.error_message }}
              </p>
            </div>
            
            <!-- 操作按钮 -->
            <div class="task-actions">
              <van-button 
                v-if="task.status === 'completed'" 
                type="primary" 
                size="small"
                @click.stop="shareTask(task)"
              >
                分享
              </van-button>
              
              <van-button 
                v-if="task.status === 'failed'" 
                type="warning" 
                size="small"
                @click.stop="retryTask(task)"
              >
                重试
              </van-button>
              
              <van-button 
                v-if="task.status === 'processing'" 
                type="default" 
                size="small"
                @click.stop="viewProgress(task)"
              >
                查看进度
              </van-button>
              
              <van-button 
                type="default" 
                size="small"
                @click.stop="deleteTask(task)"
              >
                删除
              </van-button>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
      
      <!-- 空状态 -->
      <van-empty v-if="!loading && historyList.length === 0" description="还没有生成记录">
        <van-button 
          type="primary" 
          size="small"
          @click="goToUpload"
          class="empty-btn"
        >
          开始创作
        </van-button>
      </van-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useImageStore } from '../stores/image'
import type { ImageTask } from '../types'
import { Toast, Dialog } from 'vant'

const router = useRouter()
const imageStore = useImageStore()

const activeStatus = ref('')
const historyList = ref<ImageTask[]>([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const currentPage = ref(1)

// 状态文本映射
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '排队中',
    processing: '生成中',
    completed: '已完成',
    failed: '生成失败'
  }
  return statusMap[status] || status
}

// 格式化时间
const formatTime = (timeStr?: string) => {
  if (!timeStr) return '-'
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 一分钟内
  if (diff < 60 * 1000) return '刚刚'
  
  // 一小时内
  if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000))
    return `${minutes}分钟前`
  }
  
  // 一天内
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    return `${hours}小时前`
  }
  
  // 超过一天
  return date.toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 状态筛选切换
const onStatusChange = (name: string) => {
  activeStatus.value = name
  resetList()
  loadHistory()
}

// 重置列表
const resetList = () => {
  historyList.value = []
  currentPage.value = 1
  finished.value = false
}

// 加载历史记录
const loadHistory = async () => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    const result = await imageStore.loadHistory(currentPage.value)
    
    if (result.success && result.data) {
      const newTasks = result.data.items
      
      // 根据状态筛选
      const filteredTasks = activeStatus.value 
        ? newTasks.filter(task => task.status === activeStatus.value)
        : newTasks
      
      if (currentPage.value === 1) {
        historyList.value = filteredTasks
      } else {
        historyList.value.push(...filteredTasks)
      }
      
      // 检查是否还有更多数据
      finished.value = !result.data.has_next
      
      if (result.data.has_next) {
        currentPage.value++
      }
    }
  } catch (error: any) {
    Toast.fail(error.message || '加载失败')
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  resetList()
  loadHistory()
}

// 加载更多
const onLoad = () => {
  loadHistory()
}

// 查看任务详情
const viewTask = (task: ImageTask) => {
  if (task.status === 'completed') {
    router.push(`/result/${task.id}`)
  } else if (task.status === 'processing') {
    router.push(`/generate?taskId=${task.id}`)
  } else {
    // 显示任务详情弹窗
    showTaskDetail(task)
  }
}

// 显示任务详情
const showTaskDetail = (task: ImageTask) => {
  let message = `
    <div style="text-align: left;">
      <p><strong>风格：</strong>${task.style_template?.name || '未知'}</p>
      <p><strong>状态：</strong>${getStatusText(task.status)}</p>
      <p><strong>尺寸：</strong>${task.width}×${task.height}</p>
      <p><strong>创建时间：</strong>${formatTime(task.created_at)}</p>
  `
  
  if (task.custom_prompt) {
    message += `<p><strong>自定义描述：</strong>${task.custom_prompt}</p>`
  }
  
  if (task.error_message) {
    message += `<p style="color: #ff4d4f;"><strong>错误信息：</strong>${task.error_message}</p>`
  }
  
  message += `</div>`
  
  Dialog.alert({
    title: '任务详情',
    message,
    allowHtml: true
  })
}

// 分享任务
const shareTask = (task: ImageTask) => {
  // TODO: 实现分享功能
  Toast('分享功能开发中...')
}

// 重试任务
const retryTask = (task: ImageTask) => {
  Dialog.confirm({
    title: '重新生成',
    message: '确定要重新生成这张图片吗？'
  }).then(() => {
    // 设置原图和风格
    imageStore.setUploadedImage({
      url: task.original_image_url,
      filename: 'retry.jpg'
    })
    
    if (task.style_template) {
      imageStore.setSelectedStyle(task.style_template)
    }
    
    router.push('/upload')
  })
}

// 查看进度
const viewProgress = (task: ImageTask) => {
  router.push(`/generate?taskId=${task.id}`)
}

// 删除任务
const deleteTask = (task: ImageTask) => {
  Dialog.confirm({
    title: '删除记录',
    message: '确定要删除这条记录吗？'
  }).then(() => {
    const index = historyList.value.findIndex(item => item.id === task.id)
    if (index > -1) {
      historyList.value.splice(index, 1)
      Toast.success('删除成功')
    }
  })
}

// 去上传页面
const goToUpload = () => {
  router.push('/upload')
}

onMounted(() => {
  loadHistory()
})
</script>

<style scoped>
.history-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.filter-bar {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.history-list {
  padding: 12px 16px;
}

.history-item {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.history-item:active {
  transform: translateY(1px);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.task-images {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.image-container {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
}

.image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ccc;
}

.image-label {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  font-size: 10px;
  text-align: center;
  padding: 2px;
}

.arrow {
  color: #6366f1;
  font-size: 16px;
}

.task-info {
  margin-bottom: 12px;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.task-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.task-status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  font-weight: 500;
}

.task-status.pending {
  background: #fff7e6;
  color: #fa8c16;
}

.task-status.processing {
  background: #e6f7ff;
  color: #1890ff;
}

.task-status.completed {
  background: #f6ffed;
  color: #52c41a;
}

.task-status.failed {
  background: #fff2f0;
  color: #ff4d4f;
}

.task-details {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.detail-item .van-icon {
  font-size: 12px;
}

.custom-prompt {
  font-size: 12px;
  color: #666;
  background: #f5f5f5;
  padding: 8px;
  border-radius: 6px;
  margin: 8px 0;
  display: flex;
  align-items: flex-start;
  gap: 4px;
}

.custom-prompt .van-icon {
  margin-top: 2px;
  font-size: 12px;
}

.error-message {
  font-size: 12px;
  color: #ff4d4f;
  background: #fff2f0;
  padding: 8px;
  border-radius: 6px;
  margin: 8px 0;
  display: flex;
  align-items: flex-start;
  gap: 4px;
}

.error-message .van-icon {
  margin-top: 2px;
  font-size: 12px;
}

.task-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.empty-btn {
  margin-top: 16px;
}
</style>